package com.luhe.midi.mtrk.event.midievent;

import com.luhe.midi.helper.ByteUtil;
import com.luhe.midi.helper.MidiUtil;
import com.luhe.midi.mtrk.event.Event;
import org.apache.log4j.Logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 按键下压Event：9x，频道，按键，力度
 */
public class KeyPressEvent extends MidiEvent {

    //通道：每个通道是不同的乐器
    public int channel;

    //按键：00-7F之间
    public int key;

    //力度：00-7F之间
    public int velocity;

    Logger logger = Logger.getLogger(this.getClass().getName());


    public KeyPressEvent() {
    }

    //时间差、频道、按键、力度
    public KeyPressEvent(int tick, int channel, int key, int velocity) throws IOException {
        this.tick = tick;
        this.channel = channel;
        this.key = key;
        this.velocity = velocity;
        this.len = MidiUtil.writeDynamicBytes(tick).length + 3;
    }

    public byte[] writeOutputStream(OutputStream outputStream) throws IOException {
        //键按下消息
        KeyPressEvent keyPressEvent = (KeyPressEvent) this;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        //变长度字节
        byte[] ticks = MidiUtil.writeDynamicBytes(this.tick);
        byteArrayOutputStream.write(ticks);

        //9x,x指的是通道
        byteArrayOutputStream.write((byte) (0x90 | (0xf & keyPressEvent.channel)));
        byteArrayOutputStream.write((byte) keyPressEvent.key);
        byteArrayOutputStream.write((byte) keyPressEvent.velocity);

        byte[] r = byteArrayOutputStream.toByteArray();

        this.innerByte = r;
        outputStream.write(r);

        return r;

    }


    //从流中读取
    @Override
    public Event readInputStream(InputStream inputStream) throws Exception {
        //读动态时长
        byte[] tick_bytes = MidiUtil.readDynamicIntBytes(inputStream);
        int tick = MidiUtil.readDynamicInt(tick_bytes, 0, tick_bytes.length);

        //读事件类型
        byte event[] = new byte[1];
        inputStream.read(event);

        this.tick = tick;
        this.channel = MidiUtil.getLow4((byte) event[0]);
        byte keyPress_bytes[] = new byte[2];
        inputStream.read(keyPress_bytes);
        this.key = keyPress_bytes[0];
        this.velocity = keyPress_bytes[1];
        logger.info("读按下事件：" + ByteUtil.printByte(tick_bytes) + "tick:" + tick + " , " + ByteUtil.printByte(event) + ByteUtil.printByte(keyPress_bytes));

        return this;
    }
}
